<template>
  <view class="tn-collapse">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { 
  collapseProps, 
  collapseEmits, 
  CollapseItemContext, 
  CollapseContext, 
  collapseContextKey 
} from '../../../types/tn-collapse'
import { UPDATE_MODEL_EVENT } from '../../../constants'
import { provide, reactive, ref, toRefs, watch } from 'vue'
import { castArray } from 'lodash-unified'

const props = defineProps(collapseProps)
const emits = defineEmits(collapseEmits)

// 已激活的item
const activeItem = ref(castArray(props.modelValue as (number | string | (number | string)[])))
watch(() => props.modelValue, (val) => {
  activeItem.value = castArray(props.modelValue as (number | string | (number | string)[]))
}, {
  deep: true
})

// 保存子组件信息
let fields: CollapseItemContext[] = []
// 添加子组件
const addField: CollapseContext['addField'] = (field: CollapseItemContext) => {
  // 不存在才添加
  const index = fields.indexOf(field)
  if (index === -1) {
    fields.push(field)
    if (!props?.accordion && activeItem.value.includes(fields.length - 1)) {
      field.changeStatus(true)
    } else if (props?.accordion && Number(activeItem.value[0]) === fields.length - 1) {
      field.changeStatus(true)
    }
  }
}
// 移除子组件
const removeField: CollapseContext['removeField'] = (field: CollapseItemContext) => {
  const index = fields.indexOf(field)
  if (index !== -1) {
    fields.splice(index, 1)
  }
}

// 设置激活的item
const setActiveItem = (_activeItem: (number | string)[]) => {
  activeItem.value = _activeItem
  const value = props?.accordion ? activeItem.value[0] : activeItem.value

  for (let i = 0; i < fields.length; i++) {
    if (activeItem.value.includes(i)) {
      fields[i].changeStatus(true)
    } else {
      fields[i].changeStatus(false)
    }
  }

  emits(UPDATE_MODEL_EVENT, value)
  emits('change', value)
}

// 修改子组件的折叠状态
const changeItemStatus = (id: string) => {
  const index = fields.findIndex((field) => {
    return field.id === id
  })
  if (index === -1) return
  // 判断是否为手风琴模式
  if(props?.accordion) {
    setActiveItem(index === activeItem.value[0] ? [''] : [index])
  } else {
    // 获取已激活的数据
    const _activeItem = [...activeItem.value]
    if (activeItem.value.includes(index)) {
      _activeItem.splice(_activeItem.indexOf(index), 1)
    } else {
      _activeItem.push(index)
    }
    setActiveItem(_activeItem)
  }
}

provide(
  collapseContextKey,
  reactive({
    ...toRefs(props),

    addField,
    removeField,
    changeItemStatus
  })
)
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>
</style>
